package initialize

import (
	"fmt"

	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"web_golang/user-web/global"
	"web_golang/user-web/proto"
)

func InitSrcConn() {
	consulInfo := global.ServerConfig.ConsulInfo
	userConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", consulInfo.Host, consulInfo.Port, global.ServerConfig.UserSrvInfo.Name),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Fatal("[InitSrvConn] 连接 【用户服务失败】")
		return
	}
	userSrcClient := proto.NewUserClient(userConn)
	global.UserSrvClient = userSrcClient
}

//func InitSrvConn2() {
//	cfg := api.DefaultConfig()
//	consulInfo := global.ServerConfig.ConsulInfo
//	//连接consul
//	cfg.Address = fmt.Sprintf("%s:%d", consulInfo.Host, consulInfo.Port)
//	userSrvHost := ""
//	userSrvPort := 0
//	client, err := api.NewClient(cfg)
//	if err != nil {
//		panic(err)
//	}
//	data, err := client.Agent().ServicesWithFilter(fmt.Sprintf("Service == \"%s\"", global.ServerConfig.UserSrvConfig.Name))
//	//data, err := client.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`,global.ServerConfig.UserSrvConfig.Name))
//	if err != nil {
//		panic(err)
//	}
//	for _, value := range data {
//		userSrvHost = value.Address
//		userSrvPort = value.Port
//		break
//	}
//	if userSrvHost == "" {
//		zap.S().Fatal("[InitSrvConn] 连接 【用户服务失败】")
//		return
//	}
//	//拨号连接用户grpc服务器
//	userConn, err := grpc.Dial(fmt.Sprintf("%s:%d", userSrvHost,
//		userSrvPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
//	if err != nil {
//		zap.S().Errorw("[GetUserList] 连接 【用户服务失败】",
//			"msg", err.Error(),
//		)
//	}
//	//1.后续的用户服务下线了 2.该端口了 3.改ip了   负载均衡来做
//	//2.已经事先创立好了连接，这样后续就不用进行再次tcp的三次握手
//	//3.一个连接多个groutine共用，性能-连接池
//	userSrcClient := proto.NewUserClient(userConn)
//	global.UserSrvClient = userSrcClient
//
//}
